package cn.net.yugu.doraemon.thread;

import org.slf4j.MDC;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;

/**
 * @description:
 * @author: wanghongli
 * @create: 2023-03-09 10:52:22
 */
public class YgThreadPoolMdcFilter {
    private static final String TRACE_ID = "traceId";

    public static void setSleuthTraceId(){
        String traceId = MDC.get(TRACE_ID);
        if (traceId == null || traceId.length() == 0) {
            MDC.put(TRACE_ID, UUID.randomUUID().toString());
        }
    }

    public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setSleuthTraceId();
            try {
                return callable.call();
            } finally {
                MDC.clear();
            }
        };
    }

    public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            setSleuthTraceId();
            try {
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
